package com.anjiplus.template.gaea.business.modules.quartzReport.task;


import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.utils.ApplicationContextUtils;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anjiplus.template.gaea.business.enums.SetTypeEnum;
import com.anjiplus.template.gaea.business.modules.dataset.controller.dto.DataSetDto;
import com.anjiplus.template.gaea.business.modules.dataset.service.DataSetService;
import com.anjiplus.template.gaea.business.modules.datasetparam.controller.dto.DataSetParamDto;
import com.anjiplus.template.gaea.business.modules.datasettransform.controller.dto.DataSetTransformDto;
import com.anjiplus.template.gaea.business.modules.datasettransform.dao.entity.DataSetTransform;
import com.anjiplus.template.gaea.business.modules.datasettransform.service.DataSetTransformService;
import com.anjiplus.template.gaea.business.modules.datasource.controller.dto.DataSourceDto;
import com.anjiplus.template.gaea.business.modules.datasource.dao.entity.DataSource;
import com.anjiplus.template.gaea.business.modules.datasource.service.DataSourceService;
import com.anjiplus.template.gaea.business.modules.https.service.HttpService;
import com.anjiplus.template.gaea.business.modules.quartz.task.QuartzTaskJob;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.entity.TBScheduledGaeaReport;
import com.anjiplus.template.gaea.business.modules.tbscheduledgaeareport.service.TBScheduledGaeaReportService;
import com.anjiplus.template.gaea.business.util.JdbcConstants;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.PersistJobDataAfterExecution;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@PersistJobDataAfterExecution
@DisallowConcurrentExecution

public class QuartzReportTask implements QuartzTaskJob {

    public void executeBack(JobExecutionContext context) throws JobExecutionException {
        String name = context.getJobDetail().getJobBuilder().build().getKey().getName();
//        ApplicationContext applicaiton = ApplicationContextUtils.getBean();
        DataSetTransformService dataSetTransformService = ApplicationContextUtils.getBean(DataSetTransformService.class);
        DataSourceService dataSourceService = ApplicationContextUtils.getBean(DataSourceService.class);
        DataSetService dataSetService = ApplicationContextUtils.getBean(DataSetService.class);
        TBScheduledGaeaReportService tBScheduledGaeaReportService = ApplicationContextUtils.getBean(TBScheduledGaeaReportService.class);
        QueryWrapper<TBScheduledGaeaReport> TBScheduledGaeaReportWrapper = new QueryWrapper<>();
        TBScheduledGaeaReportWrapper.eq("\"scheduled_code\"", name);
        TBScheduledGaeaReportWrapper.eq("\"delete_state\"", 0);
        //启用之后才执行定时
        TBScheduledGaeaReportWrapper.eq("\"enable_status\"", 1);
        List<TBScheduledGaeaReport> tbScheduledGaeaReports = tBScheduledGaeaReportService.list(TBScheduledGaeaReportWrapper);
        if (!CollectionUtils.isEmpty(tbScheduledGaeaReports)) {
            for (TBScheduledGaeaReport tbScheduledGaeaReport : tbScheduledGaeaReports) {
                System.out.println("定时开始执行了"+name+"===="+tbScheduledGaeaReport.getScheduledName());
                String gaeaReportCode = tbScheduledGaeaReport.getGaeaReportCode();
                JdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(JdbcTemplate.class);
                try {
                    Map<String, Object> gaeareportmap = jdbcTemplate.queryForMap("select  * from  \"gaea_report_data_set\" where \"id\" = '" + gaeaReportCode + "' ");
                    Object source_code = gaeareportmap.get("source_code");
                    Object set_code = gaeareportmap.get("set_code");
                    String relationalDataSet = "";
                    if (!StringUtils.isEmpty(source_code)) {

                        DataSourceDto dataSourceDto = new DataSourceDto();
                        dataSourceDto.setSql(gaeareportmap.get("dyn_sentence").toString());
                        dataSourceDto.setDynSentence(gaeareportmap.get("dyn_sentence").toString());
                        dataSourceDto.setSourceType(gaeareportmap.get("set_type").toString());
                        dataSourceDto.setSourceType(gaeareportmap.get("set_type").toString());
                        dataSourceDto.setSourceConfig(gaeareportmap.get("dyn_sentence").toString());
                        //4.获取数据
                        dataSourceDto.setDeleteFlag(0);

                        //1.获取数据集、参数替换、数据转换
                        DataSetDto dataSetDto = dataSetService.detailSet(set_code.toString());
                        String dynSentence;
                        if (!ObjectUtils.isEmpty(dataSetDto.getDynSentence())) {
                            dynSentence = dataSetDto.getDynSentence();
                        } else {
                            dynSentence = dataSetDto.getDynSentence();
                        }
                        relationalDataSet = dataSetDto.getRelationalDataSet();
                        //2.获取数据源
                        DataSource dataSource;
                        if (org.apache.commons.lang3.StringUtils.isNotBlank(dataSetDto.getSetType())
                                && dataSetDto.getSetType().equals(SetTypeEnum.HTTP.getCodeValue())) {
                            //http不需要数据源，兼容已有的逻辑，将http所需要的数据塞进DataSource
                            dataSource = new DataSource();
                            dataSource.setSourceConfig(dynSentence);
                            dataSource.setSourceType(JdbcConstants.HTTP);
                            String body = JSONObject.parseObject(dynSentence).getString("body");
                            if (org.apache.commons.lang3.StringUtils.isNotBlank(body)) {
                                dynSentence = body;
                            } else {
                                dynSentence = "{}";
                            }

                        }
                        dataSourceDto.setDynSentence(dynSentence);
                        List<JSONObject> data = dataSourceService.execute(dataSourceDto);
                        //5.数据转换
                        QueryWrapper<DataSetTransform> DataSetTransformWrapper = new QueryWrapper<>();
                        DataSetTransformWrapper.eq("set_code", set_code);
                        DataSetTransformWrapper.eq("delete_state", 0);
                        List<DataSetTransform> dataSetTransformList = dataSetTransformService.list(DataSetTransformWrapper);
                        List<DataSetTransformDto> dataSetTransformDtoList = new ArrayList<>();
                        for (DataSetTransform dataSetTransform : dataSetTransformList) {
                            DataSetTransformDto dataSetTransformDto = new DataSetTransformDto();
                            GaeaBeanUtils.copyAndFormatter(dataSetTransform, dataSetTransformDto);
                            dataSetTransformDtoList.add(dataSetTransformDto);
                        }
                        dataSetTransformService.transform(dataSetTransformDtoList, data, relationalDataSet);
                    } else {
                        DataSource dataSource = dataSourceService.selectOne("source_code", source_code);
                        DataSourceDto dataSourceDto = new DataSourceDto();
                        dataSourceDto.setSql(gaeareportmap.get("dyn_sentence").toString());
                        dataSourceDto.setDynSentence(gaeareportmap.get("dyn_sentence").toString());
                        BeanUtils.copyProperties(dataSource, dataSourceDto);
                        List<JSONObject> data = dataSourceService.execute(dataSourceDto);
                        List<DataSetTransform> dataSetTransformList = dataSetTransformService.list(
                                new QueryWrapper<DataSetTransform>()
                                        .lambda()
                                        .eq(DataSetTransform::getSetCode, set_code)
                                        .orderByAsc(DataSetTransform::getOrderNum)
                        );
                        List<DataSetTransformDto> dataSetTransformDtoList = new ArrayList<>();
                        dataSetTransformList.forEach(dataSetTransform -> {
                            DataSetTransformDto dataSetTransformDto = new DataSetTransformDto();
                            GaeaBeanUtils.copyAndFormatter(dataSetTransform, dataSetTransformDto);
                            dataSetTransformDtoList.add(dataSetTransformDto);
                        });
                        //执行后结果在这里打印
                        List<JSONObject> transform = dataSetTransformService.transform(dataSetTransformDtoList, data, null);
                        log.debug("执行解析后的结果打印->{}", transform);

                    }
                } catch (Exception e) {
                    continue;
                }


            }
        }
    }

    public void execute(JobExecutionContext context) throws JobExecutionException {
        String name = context.getJobDetail().getJobBuilder().build().getKey().getName();
//        ApplicationContext applicaiton = ApplicationContextUtils.getBean();
        DataSetTransformService dataSetTransformService = ApplicationContextUtils.getBean(DataSetTransformService.class);
        DataSourceService dataSourceService = ApplicationContextUtils.getBean(DataSourceService.class);
        DataSetService dataSetService = ApplicationContextUtils.getBean(DataSetService.class);
        TBScheduledGaeaReportService tBScheduledGaeaReportService = ApplicationContextUtils.getBean(TBScheduledGaeaReportService.class);
        QueryWrapper<TBScheduledGaeaReport> TBScheduledGaeaReportWrapper = new QueryWrapper<>();
        TBScheduledGaeaReportWrapper.eq("\"scheduled_code\"", name);
        TBScheduledGaeaReportWrapper.eq("\"delete_state\"", 0);
        //启用之后才执行定时
        TBScheduledGaeaReportWrapper.eq("\"enable_status\"", 1);
        List<TBScheduledGaeaReport> tbScheduledGaeaReports = tBScheduledGaeaReportService.list(TBScheduledGaeaReportWrapper);
        if (!CollectionUtils.isEmpty(tbScheduledGaeaReports)) {
            for (TBScheduledGaeaReport tbScheduledGaeaReport : tbScheduledGaeaReports) {
                System.out.println("定时开始执行了");
                String gaeaReportCode = tbScheduledGaeaReport.getGaeaReportCode();
                HttpService httpService = ApplicationContextUtils.getBean(HttpService.class);
                try {
                    httpService.sendRequest(gaeaReportCode);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }


            }
        }
    }

    /**
     * dataSetParamDtoList转map
     *
     * @param dataSetParamDtoList
     * @return
     */
    public Map<String, Object> setContextData(List<DataSetParamDto> dataSetParamDtoList) {
        Map<String, Object> map = new HashMap<>();
        if (null != dataSetParamDtoList && dataSetParamDtoList.size() > 0) {
            dataSetParamDtoList.forEach(dataSetParamDto -> map.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem()));
        }
        return map;
    }


}

